package cn.edu.csust.tysp.backend.controller;

import cn.edu.csust.tysp.backend.common.ApiPageResult;
import cn.edu.csust.tysp.backend.common.ApiResult;
import cn.edu.csust.tysp.backend.domain.Users;
import cn.edu.csust.tysp.backend.dto.RegisterMessage;
import cn.edu.csust.tysp.backend.service.UserService;
import com.alibaba.fastjson.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

/**
 * @ClassName: UserController
 * @Author: XijiaoZheng
 * @E-mail: 2516299639@qq.com
 * @Date: 2021/5/9 11:27
 * @Version: V1.0
 * @Description: 对该类的描述
 */
@RestController
public class UserController {

    @Autowired
    UserService userService;

    @GetMapping("/login")
    public JSONObject login(String username, String password) {
        if(!userService.findbyname(username))
            return ApiPageResult.error("628","不存在该账号").toJsonObject();
        if(password==null||userService.selectPassword(username,password)==null){
            return ApiPageResult.error("628","密码错误").toJsonObject();
        }
        ApiResult<Users> apiResult=new ApiResult<>(userService.selectPassword(username,password));
        apiResult.setSuccess(true);
        System.out.println(userService.selectPassword(username,password));
        return apiResult.toJsonObject();
    }

    @PostMapping("/register")
    public JSONObject register(@RequestBody JSONObject registerMessageJson) {
        RegisterMessage registerMessage = JSONObject.parseObject(registerMessageJson.toJSONString(), RegisterMessage.class);
        if(registerMessage.getUsername()==null||registerMessage.getPassword()==null){
            return ApiPageResult.error("628","账号或密码为空，注册失败").toJsonObject();
        }
        if(!registerMessage.getPassword().equals(registerMessage.getPassword2())&&registerMessage.getPassword()!=null){
            return ApiPageResult.error("628","前后两次输入的密码不一致，注册失败").toJsonObject();
        }
        if(userService.findbyname(registerMessage.getUsername()))
            return ApiPageResult.error("628","该用户已存在").toJsonObject();
        Users users=new Users();
        users.setUsername(registerMessage.getUsername());
        users.setPassword(registerMessage.getPassword());
        if(registerMessage.getNickname().equals("")){
            users.setNickname(registerMessage.getUsername());
        }else{
            users.setNickname(registerMessage.getNickname());
        }
        users.setAvatarUrl(registerMessage.getAvatarURL());
        int id=userService.insert(users);
        ApiResult<Users> apiResult=new ApiResult<>(users);
        apiResult.setSuccess(true);
        return apiResult.toJsonObject();
    }

}
